package com.jplus.core.mvc;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.jplus.core.mvc.anno.RequestMapping;
import com.jplus.core.mvc.anno.ResponseBody;
import com.jplus.core.mvc.reqeust.RequestMethod;
import com.jplus.core.utill.clazz.ClassUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestMethodAttr {
	static Logger log = LoggerFactory.getLogger(RequestMethodAttr.class);
	public RequestMethod requestMethod;
	public String requestProduces;
	public Method method;

	public ResponseBody responseBody;
	String requestMapping;
	RequestMapping classRequestMapping;
	RequestMapping methodRequestMapping;

	public static List<RequestMethodAttr> build(Class<?> controllerClass) {
		List<RequestMethodAttr> list = new ArrayList<>();
		RequestMapping cm = controllerClass.getAnnotation(RequestMapping.class);
		String classMapping = cm == null ? "" : cm.value();
		ResponseBody crb = ClassUtil.findAnnotationOne(controllerClass, ResponseBody.class);
		for (Method m : controllerClass.getMethods()) {
			RequestMapping mm = m.getAnnotation(RequestMapping.class);
			if (mm != null) {
				String requestMapping = classMapping.concat(mm.value());
				requestMapping = ("/" + requestMapping).replaceAll("//", "/");

				ResponseBody rb = m.getAnnotation(ResponseBody.class);
				RequestMethodAttr attr = new RequestMethodAttr();
				attr.method = m;
				attr.classRequestMapping = cm;
				attr.methodRequestMapping = mm;
				attr.requestMapping = requestMapping;
				attr.responseBody = rb != null ? rb : crb;

				attr.requestProduces = cm != null ? cm.produces() : "";
				attr.requestProduces = !mm.produces().equals("") ? mm.produces() : attr.requestProduces;

				attr.requestMethod = cm != null ? cm.method() : RequestMethod.ALL;
				attr.requestMethod = mm.method() != null ? mm.method() : attr.requestMethod;
				list.add(attr);

				log.info("\t>> [" + mm.method() + ":" + requestMapping + "] \t- " + controllerClass + "." + m.getName()
						+ Arrays.asList((m.getParameterTypes())));
			}
		}
		return list;
	}

}
